using static AnalyStock.DataManage.HttpClientUtility;

namespace AnalyStock.DataManage;
/// <summary>
/// 网易数据接口
/// </summary>
public static class UtilityOfQuotesMoney
{
    private enum DownDataType
    {
        FinancialIndex, CurrentDailyData, CurrentMinuteData, HistoryData
    }
    /// <summary>
    ///     获得财务指标数据
    /// </summary>
    /// <param name="stockcode"></param>
    /// <returns></returns>
    public static async Task<DataTable> GetFinancialIndicators(string stockcode)
    {
        var uri = SeleUriAddress(DownDataType.FinancialIndex, new[] { stockcode[..6], "", "" });
        var result = await HttpClientGetAsync(uri).ConfigureAwait(false);
        if (string.IsNullOrEmpty(result)) throw new Exception(result);
        return result.ConvertToDataTable();
    }

    /// <summary>
    ///     当日在线及时交易信息
    /// </summary>
    /// <param name="stockcode"></param>
    /// <returns></returns>
    public static async Task<DailyOfQutoes> GetTodayTradeData(string stockcode)
    {
        var uri = SeleUriAddress(DownDataType.CurrentDailyData, new[] { stockcode[..6], "", "" });
        var result = await HttpClientGetAsync(uri).ConfigureAwait(false);
        if (string.IsNullOrEmpty(result)) throw new Exception(result);
        var josntxtRange = new Range(result.IndexOf(":{") + 1, result.IndexOf("})"));
        var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
        return JsonSerializer.Deserialize<DailyOfQutoes>(result[josntxtRange], options);
    }

    public static async Task<MinuteOfQutoes> GetMintueTradeData(string stockcode)
    {
        var uri = SeleUriAddress(DownDataType.CurrentMinuteData, new[] { stockcode[..6], "", "" });
        var result = await HttpClientGetAsync(uri).ConfigureAwait(false);
        if (string.IsNullOrEmpty(result)) throw new Exception(result);
        var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
        return JsonSerializer.Deserialize<MinuteOfQutoes>(result, options);
    }

    // param string stockcode, string startdate,string enddate
    private static Uri SeleUriAddress(DownDataType downType, string[] stockparam)
    {
        //深圳 1 沪市6 开头 0 
        var codeOfMarket = stockparam[0].StartsWith("6") ? "0" : "1";
        return new Uri(
            downType switch
            {
                DownDataType.HistoryData =>
                    "http://quotes.money.163.com/service/chddata.html?"
                     + $"code={codeOfMarket}{stockparam[0]}&start={stockparam[1]}&end={stockparam[2]}"
                     + "&fields=TCLOSE;HIGH;LOW;TOPEN;LCLOSE;CHG;PCHG;VOTURNOVER;VATURNOVER",
                DownDataType.FinancialIndex =>
                    $"http://quotes.money.163.com/service/zycwzb_{stockparam[0]}.html?type=report",
                DownDataType.CurrentDailyData =>
                    $"http://api.money.126.net/data/feed/{codeOfMarket}{stockparam[0]},money.api",
                DownDataType.CurrentMinuteData =>
                    $"http://img1.money.126.net/data/hs/time/today/{codeOfMarket}{stockparam[0]}.json",
                _ => throw new NotImplementedException()
            });
    }

    /// <summary>
    ///     获取网易财务数据转化为DataTable格式
    /// </summary>
    /// <param name="result"></param>
    /// <returns></returns>
    private static DataTable ConvertToDataTable(this string result)
    {
        var strLines = result.Replace("\t", string.Empty)
            .Replace("--", "0") //ֵ替换为0
            .Replace("-", string.Empty) //日期格式转换YYYY-MM-dd 到yyyyMMdd
            .Trim()
            .Split("\r\n");
        var lineID = 0; //行编号
        DataTable dataTable = new();
        foreach (var line in strLines)
        {
            var cellValue = line.Trim().Split(",");
            dataTable.Columns.Add(cellValue[0]); //第一列是field名            
            for (var i = 1; i < cellValue.Length; i++) //后面列是每期的值,i为各期值编号
            {
                if (lineID == 0) //如果是第一个指标，一次性增加所有数据行
                {
                    if (!string.IsNullOrWhiteSpace(cellValue[i])) //防止有些空值行  
                    {
                        var newDr = dataTable.NewRow();
                        newDr[lineID] = cellValue[i];
                        dataTable.Rows.Add(newDr);
                    }
                }
                else
                {
                    if (!string.IsNullOrWhiteSpace(cellValue[i]))
                    {
                        dataTable.Rows[i - 1][lineID] = cellValue[i];
                    }
                }
            }

            lineID++;
        }

        return dataTable;
    }


}